package com.chenxin.quartz.task.stock;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.wms.domain.SpuEntity;
import com.chenxin.wms.domain.StockEntity;
import com.chenxin.wms.mapper.SpuMapper;
import com.chenxin.wms.mapper.StockMapper;
import com.chenxin.wms.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Component("overdueTask")
public class OverdueTask {
    //    创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private StockMapper stockMapper;

    public void overdueStock() {
        lock.lock();
        try {
            log.info("执行overdueStock任务");
            QueryWrapper<StockEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("lock_status", "2");
            List<StockEntity> stockEntities = stockMapper.selectList(queryWrapper);

            if (stockEntities.size() == 0) {
                return;
            }
            for (StockEntity stockEntity : stockEntities) {
                QueryWrapper<SpuEntity> spuQueryWrapper = new QueryWrapper<>();
                spuQueryWrapper.eq("spu_no", stockEntity.getSpuNo());
                SpuEntity spuEntity = spuMapper.selectOne(spuQueryWrapper);
                Long qualityDays = spuEntity.getQualityDays();

                Date createDate = stockEntity.getCreateDate(); // 假设返回的是 Date 类型
                LocalDateTime createDateTime = createDate.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                // 当前时间
                LocalDateTime now = LocalDateTime.now();

                // 计算相差天数
                Long daysDifference = java.time.Duration.between(createDateTime, now).toDays();

                // 判断是否超时
                if (daysDifference >= qualityDays) {
                    stockEntity.setLockStatus(2);
                    stockEntity.setLockReason("超库龄期");
                    stockEntity.setUpdateDate(new Date());
                    stockMapper.updateById(stockEntity);
                }
            }
        } catch (Exception e) {
            log.error("执行overdueStock任务异常:{}", e.getMessage());
        } finally {
            lock.unlock();
        }
    }
}
